package client.commands;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import client.IGameState;
import client.Player;
import client.PriorityMessageQueue;
import client.StateContext;

public class SaveGameCommand implements ISubCommand {

	private Player player;

	public SaveGameCommand(Player player) {
		this.player = player;
	}

	@Override
	public void execute(StateContext state) {
		String filename = "savedGame.txt";
		File old = new File(filename);
		old.delete();
		File newFile = null;
		System.out.println("File ....");
		PriorityMessageQueue.addMessage("opening file");
		try {
			newFile = new File(filename);
			boolean exist = newFile.createNewFile();
			System.out.println("File opened successfully.");
		} catch (IOException ioError) {
			ioError.printStackTrace();
		}
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			if (newFile != null) {
				fos = new FileOutputStream(newFile);
				oos = new ObjectOutputStream(fos);
				oos.writeObject(player);
				oos.close();
				System.out.println("File created successfully.");
				PriorityMessageQueue.addMessage("Game saved successfully");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public IGameState getSubState() {
		return null;
	}

	public String toString() {
		return "Save Game";
	}

}
